package org.todo.controller;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.PortletRequest;

import org.springframework.validation.BindException;
import org.springframework.web.portlet.bind.PortletRequestUtils;
import org.springframework.web.portlet.mvc.SimpleFormController;

import org.todo.domain.Category;
import org.todo.service.CategoryService;

/**
 * Controller that handles the add and edit action requests for categories
 * @author Matthias Braunhofer
 */
public class EditCategoryController extends SimpleFormController {
    //injected dependency
    private CategoryService categoryService;
  
    public EditCategoryController() {
        setCommandClass(Category.class);
    }

    /**
     * Prepares a Category object to be bound to the category form
     * @param request
     * @return
     * @throws java.lang.Exception
     */
    @Override
    protected Object formBackingObject(PortletRequest request) throws Exception {
        int categoryId = PortletRequestUtils.getIntParameter(request, "categoryId", -1);

        Category category = null;
        if (categoryId < 0) {
            category = new Category();
            category.setOwner(ControllerUtil.getUserName(request));
        } else {
            category = categoryService.getCategory(categoryId);
        }
        
        if(category == null) {
            throw new PortletException("Category not found");
        }

        return category;
    }

    /**
     * Action handler that handles the submit action of the category form
     * @param request
     * @param response
     * @param command
     * @param bindException
     * @throws java.lang.Exception
     */
    @Override
    protected void onSubmitAction(ActionRequest request, ActionResponse response, Object command, BindException bindException) throws Exception {
        Category category = (Category) command;
        categoryService.addCategory(category);

        //map rendering phase to todosController
        response.setRenderParameter("action", "todos");
    }

    public void setCategoryService(CategoryService categoryService) {
        this.categoryService = categoryService;
    }
}
